import React, { useState } from 'react';
import { Card, Button, Upload, message, Progress, Row, Col } from 'antd';
import type { UploadProps, UploadFile } from 'antd';
import { InboxOutlined } from '@ant-design/icons';

const { Dragger } = Upload;

const BatchImageCropping: React.FC = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [processing, setProcessing] = useState<boolean>(false);
  const [progress, setProgress] = useState<number>(0);
  const [processedImages, setProcessedImages] = useState<string[]>([]);

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    action: '/api/upload',
    onChange(info) {
      const { fileList: newFileList } = info;
      // 使用类型断言确保类型兼容性
      setFileList(newFileList as UploadFile[]);
    },
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error(`${file.name} 不是有效的图片文件！`);
        return Upload.LIST_IGNORE;
      }
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error(`${file.name} 大小不能超过10MB！`);
        return Upload.LIST_IGNORE;
      }
      return true;
    },
  };

  const handleBatchCropping = () => {
    if (fileList.length === 0) {
      message.warning('请先上传图片');
      return;
    }

    setProcessing(true);
    setProgress(0);
    setProcessedImages([]);

    // 模拟批量抠图进度
    const interval = setInterval(() => {
      setProgress((prevProgress) => {
        const newProgress = prevProgress + 5;
        if (newProgress >= 100) {
          clearInterval(interval);
          setProcessing(false);
          message.success('批量抠图完成');
          // 在实际应用中，这里会使用AI处理后的图片URL列表
          setProcessedImages(fileList.map(file => URL.createObjectURL(file.originFileObj as File)));
          return 100;
        }
        return newProgress;
      });
    }, 200);
  };

  const handleDownloadAll = () => {
    message.info('开始打包下载所有处理后的图片');
    // 实际应用中，这里会实现批量下载功能
  };

  return (
    <div className="p-4">
      <h2 className="text-xl font-bold mb-4">批量抠图</h2>
      <Card title="上传图片" className="mb-4">
        <Dragger {...uploadProps} fileList={fileList}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽多个图片文件到此区域上传</p>
          <p className="ant-upload-hint">
            支持批量上传图片文件，单个文件不超过10MB
          </p>
        </Dragger>
      </Card>

      <div className="mb-4">
        <Button type="primary" onClick={handleBatchCropping} loading={processing} block>
          开始批量抠图
        </Button>
      </div>

      {processing && (
        <Card title="抠图进度" className="mb-4">
          <Progress percent={progress} status="active" />
          <div className="text-center text-sm text-gray-500 mt-2">
            正在处理 {fileList.length} 张图片，请稍候...
          </div>
        </Card>
      )}

      {processedImages.length > 0 && (
        <Card title="抠图结果" className="mb-4">
          <div className="flex justify-end mb-4">
            <Button onClick={handleDownloadAll}>下载全部</Button>
          </div>
          <Row gutter={[16, 16]}>
            {processedImages.map((imageUrl, index) => (
              <Col key={index} xs={24} sm={12} md={8} lg={6}>
                <Card hoverable className="h-full">
                  <img 
                    alt={`抠图结果 ${index + 1}`} 
                    src={imageUrl}
                    className="w-full h-auto max-h-[200px] object-contain" style={{ 
                      maxWidth: '100%', 
                      maxHeight: '200px',
                      margin: '0 auto'
                    }}
                  />
                  <div className="flex justify-center mt-2">
                    <Button size="small">下载</Button>
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        </Card>
      )}

      <div className="text-sm text-gray-500 mt-4">
        <p>• 支持JPG、PNG、WEBP等常见图片格式</p>
        <p>• 一次性最多支持50张图片批量处理</p>
        <p>• 处理速度取决于图片数量和服务器性能</p>
      </div>
    </div>
  );
};

export default BatchImageCropping;